package ElectricCraft.model;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * ModelPackage class contains list of models.
 */
public final class ModelPackage {
    public final ModelGroup groups = new ModelGroup("Model Package");

    public static final int OLD_VERSION_0_1   = 0x0001;
    public static final int VERSION = 0x0002;

    public void save(String filename) throws IOException {
        FileChannel channel = null;

        try {
            channel = new FileOutputStream(filename).getChannel();
            ByteBuffer buffer = ByteBuffer.allocate(4096);

            buffer.putInt(VERSION);

            groups.save(channel, buffer);

            buffer.flip();
            channel.write(buffer);
            buffer.clear();
        }
        finally {
            if (channel != null) {
                channel.close();
            }
        }
    }

    public void load(String filename) throws Exception {
        InputStream stream = null;

        try {
            stream = new BufferedInputStream(new FileInputStream(filename));
            ByteBuffer buffer = ByteBuffer.allocate(4096);

            int res = stream.read(buffer.array(), 0, 4);
            assert res == 4;

            int version = buffer.getInt(0);
            if (version != VERSION && version != OLD_VERSION_0_1) {
                throw new Exception("Version mismatch");
            }

            groups.load(version, stream, buffer);
        }
        finally {
            if (stream != null) {
                stream.close();
            }
        }
    }
}
